#!/usr/bin/ruby
$:.unshift File.join(File.dirname(__FILE__))
require 'AWS/SQS'
require 'basic_configuration'
require 'aws_context'
require 'pp'

# Receive and display a message from the given queue.

if ARGV[0] == '-?' || ARGV.size != 1 then
  puts "usage: receive-queue name"
  exit 1
end
name=ARGV[0]

Signal.trap("INT") do
  exit 2
end

config = BasicConfiguration.new
sqs = AwsContext.instance.sqs(*config.keys)
begin
  url = sqs.list_queues(name).first
  if url.nil? 
    puts "queue not found: #{name}"
    exit 1
  else  
    res = sqs.receive_messages(url)
    if res.nil? || res.length == 0
      puts "no messages #{name}"
    else
      #pp res
      puts "#{res[0][:body]}"
      sqs.delete_message(url, res[0][:receipt_handle])
    end
  end
rescue
  puts "error #{$!} #{name}"
  exit 1
end

